﻿namespace KinonekoSoftware.CodariaDB.Documents.DataParts
{
    public class PartEngine : _Delta<DataPart>
    {
        public IEnumerable<DataPart> Get(string documentID) => InsideDB.Find(x => x.DocumentID == documentID);

        public void AddParts(IEnumerable<DataPart> parts)
        {
            if (parts is null)
            {
                return;
            }

            var availableParts = parts.Where(x => string.IsNullOrEmpty(x.DocumentID));

            foreach (var part in availableParts)
            {
                Modified(part);
                InsideDB.Insert(part);
            }

        }

        public void AddPart(DataPart part)
        {
            if (part is null || string.IsNullOrEmpty(part.DocumentID))
            {
                return;
            }

            Modified(part);
            InsideDB.Insert(part);
        }


        public void UpdateParts(IEnumerable<DataPart> parts)
        {
            if (parts is null)
            {
                return;
            }

            var availableParts = parts.Where(x => string.IsNullOrEmpty(x.DocumentID));

            foreach (var part in availableParts)
            {
                Modified(part);
                InsideDB.Update(part);
            }

        }

        public void UpdatePart(DataPart part)
        {
            if (part is null || string.IsNullOrEmpty(part.DocumentID))
            {
                return;
            }

            Modified(part);
            InsideDB.Update(part);
        }


        public void RemoveParts(IEnumerable<DataPart> parts)
        {
            if (parts is null)
            {
                return;
            }

            var availableParts = parts.Where(x => string.IsNullOrEmpty(x.DocumentID));

            foreach (var part in availableParts)
            {
                Modified(part);
                InsideDB.Delete(part.Id);
            }

        }

        public void RemovePart(DataPart part)
        {
            if (part is null || string.IsNullOrEmpty(part.DocumentID))
            {
                return;
            }

            Modified(part);
            InsideDB.Delete(part.Id);
        }

        public override string GetCollectionName() => CollectionNames.DataPartDB;

        public override string EngineID => EngineNames.DataPart;
        public bool Has(string pid, string did) => InsideDB.Exists(
            Query.And(
                Query.EQ(Codaria.ID, pid),
                Query.EQ(nameof(DataPart.DocumentID), did)));
    }
}